<?php
/**
 * Created by PhpStorm.
 * User: Guo
 * Date: 2017/9/22
 * Time: 21:51
 */

namespace app\common\model;


use app\common\lib\Data;

class Comment extends BaseModel
{
    protected $table = 'ng_comments';

    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    protected $autoWriteTimestamp = 'datetime';

    protected $deleteTime = 'deleted_at';

    protected $hidden = ['updated_at', 'deleted_at'];

    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id');
    }

    public function article()
    {
        return $this->belongsTo('Article', 'article_id', 'id');
    }

    /**
     * 获取全部数据
     * @param string $type      tree获取树形结构 level获取层级结构
     * @param string $order     排序方式
     * @param string $name      字段名
     * @param string $child     主键id
     * @param string $parent    父id
     * @return array|mixed
     */
    public static function getTreeData($article_id, $type='tree', $order='', $name='name', $child='id', $parent='pid')
    {
        // 判断是否需要排序
        if(empty($order)){
            $data = self::where(['article_id'=>$article_id])->with('user.image')->select()->toArray();
        }else{
            $data = self::all(function ($query) use ($order,$article_id){
                $query->where(['article_id'=>$article_id])
                ->order($order,'asc');
            }, 'user.image')->toArray();
        }
        // 获取树形或者结构数据
        if($type == 'tree'){
            $data = Data::tree($data, $name, $child, $parent);
        }elseif($type = "level"){
            $data = Data::channelLevel($data, 0, '&nbsp;', $child);
        }
        return $data;
    }

}